package com.xh.bussiness.thirdapi.xinzhou.service.impl;

import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.xh.bussiness.system.bean.dto.StudentBean;
import com.xh.bussiness.system.model.Student;
import com.xh.bussiness.system.service.IStudentService;
import com.xh.bussiness.thirdapi.xinzhou.bean.request.XzGroupScheduleRequest;
import com.xh.bussiness.thirdapi.xinzhou.bean.request.XzGroupRequest;
import com.xh.bussiness.thirdapi.xinzhou.bean.request.XzScheduleRequest;
import com.xh.bussiness.thirdapi.xinzhou.bean.request.XzStudentInfoRequest;
import com.xh.bussiness.thirdapi.xinzhou.config.XzConfig;
import com.xh.bussiness.thirdapi.xinzhou.constant.XinzhouConstant;
import com.xh.bussiness.thirdapi.xinzhou.model.*;
import com.xh.bussiness.thirdapi.xinzhou.service.IXinzhouTmsService;
import com.xh.bussiness.tms.model.Class;
import com.xh.bussiness.tms.service.IClassManageService;
import com.xh.one2one.base.model.OneSchool;
import com.xh.one2one.base.service.IOneSchoolService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.CollectionUtils;
import org.springframework.util.StringUtils;
import org.springframework.web.client.RestTemplate;

import java.net.URLEncoder;
import java.util.*;

/**
 * @author theV
 */

@Service
public class XinzhouTmsServiceImpl implements IXinzhouTmsService {

    @Autowired
    private XzConfig config;
    @Autowired
    private RestTemplate restTemplate;
    @Autowired
    private IClassManageService classServce;
    @Autowired
    private IStudentService studentService;
    @Autowired
    private IOneSchoolService oneSchoolService;

    @Override
    public List queryGroupList(XzGroupRequest request) {
        String forEntity = doRemoteRequest(XinzhouConstant.GET_GROUP);
        if(!StringUtils.isEmpty(forEntity)){
            List<XzGroup> xzGroups = JSON.parseArray(forEntity, XzGroup.class);
            if(!CollectionUtils.isEmpty(xzGroups)){
                syncGrades(xzGroups);
                return xzGroups;
            }
        }
        return Collections.EMPTY_LIST;
    }

    private void syncGrades(List<XzGroup> xzGroups) {
        List<Class> classList = new ArrayList<>();
        for (int i = 0; i < xzGroups.size(); i++) {
            XzGroup group = xzGroups.get(i);

            Class clazz = new Class();
            clazz.setThirdId(group.getGroupId());
            clazz.setSource("新舟TMS");
            clazz.setTitle(group.getGroupName());
            clazz.setStatus(0);

            classList.add(clazz);
            if(classList.size() > 1000){
                classServce.insert(clazz);
                classList = new ArrayList<>();
            }
        }
    }

    @Override
    public List<XzTeacherInfo> getTeacherByMobile(String mobile) {
        String requestUrl = XinzhouConstant.GET_TEACHERINFO +"?mobile="+mobile;
        String forEntity = doRemoteRequest(requestUrl);
        if(!StringUtils.isEmpty(forEntity)){
            List<XzTeacherInfo> xzTeacherInfos = JSON.parseArray(forEntity,XzTeacherInfo.class);
            if(!CollectionUtils.isEmpty(xzTeacherInfos)){
                return xzTeacherInfos;
            }
        }

        return null;
    }

    @Override
    public List querySchedule(XzScheduleRequest request) {
        StringJoiner joiner = createRequestParam(request.getTeacherid(), request.getClassDateTimeFrom_begin(), request.getClassDateTimeFrom_end(), request.getGroupId());
        if(!StringUtils.isEmpty(request.getStudentId())){
            joiner.add("studentId="+request.getStudentId());
        }
        if(!StringUtils.isEmpty(request.getScheduleInstanceOTOType())){
            joiner.add("scheduleInstanceOTOType="+request.getScheduleInstanceOTOType());
        }
        String requestUrl = XinzhouConstant.GET_SCHEDULEINSTANCE + joiner.toString();
        String resultStr = doRemoteRequest(requestUrl);
        if(!StringUtils.isEmpty(resultStr)){
            List<XzSchedule> xzSchedules = JSON.parseArray(resultStr, XzSchedule.class);
            return xzSchedules;
        }
        return Collections.EMPTY_LIST;
    }

    public StringJoiner createRequestParam(String teacherid, String classDateTimeFrom_begin, String classDateTimeFrom_end, String groupId) {
        StringJoiner joiner = new StringJoiner("&","?","");
        if(!StringUtils.isEmpty(teacherid)){
            joiner.add("teacherid="+ teacherid);
        }
        if(!StringUtils.isEmpty(classDateTimeFrom_begin)){
            joiner.add("classDateTimeFrom_begin="+ classDateTimeFrom_begin);
        }
        if(!StringUtils.isEmpty(classDateTimeFrom_end)){
            joiner.add("classDateTimeFrom_end="+ classDateTimeFrom_end);
        }
        if(!StringUtils.isEmpty(groupId)){
            joiner.add("groupId="+ groupId);
        }
        return joiner;
    }

    @Override
    public List querySchedule(XzGroupScheduleRequest request) {
        StringJoiner joiner = createRequestParam(request.getTeacherid(), request.getClassDateTimeFrom_begin(), request.getClassDateTimeFrom_end(), request.getGroupId());

        String requestUrl = XinzhouConstant.GET_GROUPOTOINSTANCE + joiner.toString();
        String resultStr = doRemoteRequest(requestUrl);
        if(!StringUtils.isEmpty(resultStr)){
            List<XzGroupSchedule> xzGroupSchedules = JSON.parseArray(resultStr, XzGroupSchedule.class);
            return xzGroupSchedules;
        }
        return Collections.EMPTY_LIST;
    }

    @Override
    public List queryStudents(XzStudentInfoRequest request) throws Exception {
        StringJoiner joiner = new StringJoiner("&","?","");
        if(!StringUtils.isEmpty(request.getStudentId())){
            joiner.add("studentId="+request.getStudentId());
        }
        if(!StringUtils.isEmpty(request.getMobile())){
            joiner.add("mobile="+request.getMobile());
        }
        if(!StringUtils.isEmpty(request.getStudentName())){
            joiner.add("studentName="+ URLEncoder.encode(request.getStudentName(),"UTF-8"));
        }
        if(!StringUtils.isEmpty(request.getSchoolIds())){
            joiner.add("schoolIds="+ request.getSchoolIds());
        }
        List<XzStudentInfo> retList = new ArrayList<>();
        int pageNo = 0;
        int pageSize = 100;
        boolean flag = false;
        if(null != request.getSearchType()){
            flag = true;
        }
        do {
            joiner.add("offset="+ pageNo);
            joiner.add("pageSize="+ pageSize);
            String requestUrl = XinzhouConstant.GET_STUDENT_LIST + joiner.toString();
            String resultStr = doRemoteRequest(requestUrl);
            if(!StringUtils.isEmpty(resultStr)){
                List<XzStudentInfo> xzStudentInfos = JSON.parseArray(resultStr, XzStudentInfo.class);
                if(!CollectionUtils.isEmpty(xzStudentInfos)){
                    syncStudents(xzStudentInfos);
                    retList.addAll(xzStudentInfos);
                }

            }else{
                break;
            }
            pageNo++;
            if(flag){
                joiner =  new StringJoiner("&","?","");
            }
        }while (flag);

        return retList ;
    }

    @Override
    public List queryStudentRemainContactHour(XzStudentInfoRequest request) throws Exception {

        StringJoiner joiner = new StringJoiner("&","?","");
        if(!StringUtils.isEmpty(request.getStudentId())){
            joiner.add("studentId="+request.getStudentId());
        }

        String requestUrl = XinzhouConstant.GET_REMAINCONTACTHOUR + joiner.toString();
        String resultStr = doRemoteRequest(requestUrl);
        if(!StringUtils.isEmpty(resultStr)){
            List<XzRemainContactHour> xzRemainContactHourList = JSON.parseArray(resultStr, XzRemainContactHour.class);
            if(!CollectionUtils.isEmpty(xzRemainContactHourList)){

            }
            return xzRemainContactHourList;
        }
        return Collections.EMPTY_LIST;
    }

    @Override
    public List synSchools() {

        String resultStr = doRemoteRequest(XinzhouConstant.GET_SCHOOL);
        if(!StringUtils.isEmpty(resultStr)){
            List<XzSchool> xzSchoolList = JSON.parseArray(resultStr, XzSchool.class);
            if(!CollectionUtils.isEmpty(xzSchoolList)){
                syncSchools(xzSchoolList);
            }
            return xzSchoolList;
        }
        return Collections.EMPTY_LIST;
    }

    @Override
    public List queryStudentContract(XzStudentInfoRequest request) {
        StringJoiner joiner = new StringJoiner("&","?","");
        if(!StringUtils.isEmpty(request.getStudentId())){
            joiner.add("studentId="+request.getStudentId());
        }

        String requestUrl = XinzhouConstant.GET_CONTRACT + joiner.toString();
        String resultStr = doRemoteRequest(requestUrl);
        if(!StringUtils.isEmpty(resultStr)){
            List<XzContract> xzContractList = JSON.parseArray(resultStr, XzContract.class);
            if(!CollectionUtils.isEmpty(xzContractList)){

            }
            return xzContractList;
        }
        return Collections.EMPTY_LIST;
    }

    private void syncSchools(List<XzSchool> xzSchoolList) {
        List<OneSchool> list = new ArrayList<>();
        for (int i = 0; i < xzSchoolList.size(); i++) {
            XzSchool xzSchool = xzSchoolList.get(i);
            QueryWrapper<OneSchool> qw = new QueryWrapper();
            qw.eq("third_id",xzSchool.getSchoolId());
            OneSchool old = oneSchoolService.selectFirst(qw);
            if(null == old){
                OneSchool school = new OneSchool();
                school.setSchoolName(xzSchool.getFullName());
                school.setThirdId(xzSchool.getSchoolId());
                school.setSchoolNo(xzSchool.getSchoolNo());
                school.setSimpleName(xzSchool.getSimpleName());
                school.setProvince(xzSchool.getProvince());
                school.setCity(xzSchool.getCity());
                school.setCityLetter(xzSchool.getCityLetter());
                list.add(school);
            }
        }
        oneSchoolService.batchInsert(list);
    }

    @Transactional(rollbackFor = Exception.class)
    void syncStudents(List<XzStudentInfo> xzStudentInfos) {
        for (int i = 0; i < xzStudentInfos.size(); i++) {
            XzStudentInfo xzStudentInfo = xzStudentInfos.get(i);

            QueryWrapper<Student> qw = new QueryWrapper();
            qw.eq("third_id",xzStudentInfo.getStudentId());
            Student stu = studentService.selectFirst(qw);
            if(null == stu){
                StudentBean student = new StudentBean();
                student.setThirdId(xzStudentInfo.getStudentId());
                student.setName(xzStudentInfo.getStudentName());
                student.setFatherPhone(xzStudentInfo.getMobile());
                student.setMotherPhone(xzStudentInfo.getMobile());
                student.setSource(2);
                studentService.addStudent(student);
            }
        }
    }


    public String doRemoteRequest(String requestUrl) {
        StringBuffer buffer = new StringBuffer();
        config.getTmsHosts().forEach(url->{
            String uri = url + XinzhouConstant.API_prefix + requestUrl;
            String dataObj = restTemplate.getForObject(uri, String.class);
            if(!StringUtils.isEmpty(dataObj)){
                buffer.append(dataObj);
            }
        });
        String data = buffer.toString().replace("][", ",");
        return data;
    }
}
